import * as Stats from 'stats.js'
import { isFunction } from '@ecs/index'

// @ts-ignore
const stats = new Stats()
stats.showPanel(0)
stats.dom.style.zIndex = '10'
stats.dom.style.top = '5vw'
stats.dom.style.left = '75vw'
document.body.appendChild(stats.dom)
function update() {
  stats.begin()
  stats.end()
  requestAnimationFrame(update)
}
requestAnimationFrame(update)

type ResourceItem = {
  key: string
  type: 'image' | 'json'
  src: string
}

const resource: ResourceItem[] = [
  { key: 'sprites', type: 'image', src: './assets/sprites.png' },
  { key: 'start', type: 'image', src: './assets/start.png' },
  { key: 'spritesData', type: 'json', src: './assets/spritesData.json' }
]

/**
 * 资源加载类
 * @description 保证游戏是在资源加载完成后开始主循环
 */
class Loader {
  /**
   * 资源加载钩子函数
   * @param cb callback
   * @returns 无
   */
  public onLoaded(cb: (map: Map<string, unknown>) => void): void {
    const map = new Map<string, unknown>()
    resource.forEach(item =>
      this.loadFile(item, response => {
        map.set(item.key, response ?? null)
        if (resource.length === map.size) {
          isFunction(cb) && cb(map)
        }
      })
    )
  }

  /**
   * 资源加载
   * @param item 资源项
   * @param onFinish 加载结果
   * @returns 无
   */
  private loadFile(
    item: ResourceItem,
    onFinish: (response?: HTMLImageElement | object) => void
  ): void {
    if (item.type === 'image') {
      const image = new Image()
      image.src = item.src
      image.onload = () => onFinish(image)
      image.onerror = () => onFinish(null)
    } else {
      const xhr = new XMLHttpRequest()
      xhr.responseType = 'json'
      xhr.open('GET', item.src, true)
      xhr.onload = () => onFinish(xhr.response)
      xhr.onerror = () => onFinish(null)
      xhr.send()
    }
  }
}

export default new Loader()
